<template>
  <div class="course-detail-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      :title="courseDetail?.title || '课程详情'" 
      left-arrow 
      @click-left="onClickLeft" 
      fixed 
      placeholder
    >
      <template #right>
        <van-icon name="share-o" @click="handleShare" />
      </template>
    </van-nav-bar>

    <!-- 主内容区域 -->
    <div class="page-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <van-loading size="24px" color="#1989fa">加载中...</van-loading>
      </div>

      <!-- 课程详情内容 -->
      <div v-else-if="courseDetail" class="course-content">
        <!-- 课程封面和基本信息 -->
        <div class="course-header">
          <div class="course-cover">
            <van-image
              :src="courseDetail.cover"
              fit="cover"
              :alt="courseDetail.title"
              class="cover-image"
            />
            <div class="play-overlay" @click="playIntroVideo">
              <van-icon name="play-circle-o" size="48" color="#fff" />
              <span class="play-text">播放介绍</span>
            </div>
          </div>

          <div class="course-info">
            <h1 class="course-title">{{ courseDetail.title }}</h1>
            <p class="course-description">{{ courseDetail.description }}</p>

            <div class="course-meta">
              <div class="meta-item">
                <van-icon name="user-o" />
                <span>{{ courseDetail.instructor }}</span>
              </div>
              <div class="meta-item">
                <van-icon name="star" color="#ffd21e" />
                <span>{{ courseDetail.rating }}</span>
              </div>
              <div class="meta-item">
                <van-icon name="clock-o" />
                <span>{{ formatDuration(courseDetail.duration) }}</span>
              </div>
              <div class="meta-item">
                <van-icon name="friends-o" />
                <span>{{ courseDetail.student_count }}人学习</span>
              </div>
            </div>

            <div class="difficulty-tag">
              <van-tag :type="getDifficultyType(courseDetail.difficulty)">
                {{ getDifficultyText(courseDetail.difficulty) }}
              </van-tag>
            </div>
          </div>
        </div>

      <!-- 课程进度 -->
      <div class="progress-section" v-if="userProgress">
        <div class="progress-header">
          <h3>学习进度</h3>
          <span class="progress-text">{{ userProgress.progress }}%</span>
        </div>
        <van-progress 
          :percentage="userProgress.progress" 
          color="#1989fa"
          track-color="#f2f3f5"
        />
        <div class="progress-info">
          <span>已完成 {{ userProgress.completedLessons }}/{{ userProgress.totalLessons }} 课时</span>
          <span>学习时长 {{ formatStudyTime(userProgress.studyTime) }}</span>
        </div>
      </div>

      <!-- 课程章节列表 -->
      <div class="lessons-section">
        <h3 class="section-title">课程内容</h3>
        <div class="lessons-list">
          <!-- 按章节显示课时 -->
          <div v-for="chapter in courseChapters" :key="chapter.id" class="chapter-section">
            <div class="chapter-header">
              <h4 class="chapter-title">{{ chapter.title }}</h4>
              <p class="chapter-description">{{ chapter.description }}</p>
            </div>
            <div
              v-for="(lesson, index) in chapter.lessons"
              :key="lesson.id"
              class="lesson-item"
              @click="playLesson(lesson)"
            >
              <div class="lesson-number">{{ index + 1 }}</div>
              <div class="lesson-content">
                <h4 class="lesson-title">{{ lesson.title }}</h4>
                <p class="lesson-description">{{ lesson.description }}</p>
                <div class="lesson-meta">
                  <span class="lesson-duration">{{ formatDuration(lesson.duration) }}</span>
                  <van-tag v-if="lesson.isCompleted" type="success" size="mini">已完成</van-tag>
                  <van-tag v-else-if="lesson.isLocked" type="default" size="mini">未解锁</van-tag>
                  <van-tag v-if="lesson.is_free" type="primary" size="mini">免费</van-tag>
                </div>
              </div>
              <div class="lesson-action">
                <van-icon
                  :name="lesson.isCompleted ? 'success' : lesson.isLocked ? 'lock' : 'play-circle-o'"
                  :color="lesson.isCompleted ? '#07c160' : lesson.isLocked ? '#969799' : '#1989fa'"
                  size="24"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 相关推荐 -->
      <div class="related-section">
        <h3 class="section-title">相关推荐</h3>
        <div class="related-courses">
          <div 
            v-for="course in relatedCourses" 
            :key="course.id"
            class="related-course"
            @click="goToCourse(course.id)"
          >
            <van-image
              :src="course.cover"
              fit="cover"
              :alt="course.title"
              class="related-cover"
            />
            <div class="related-info">
              <h4 class="related-title">{{ course.title }}</h4>
              <div class="related-meta">
                <van-icon name="star" color="#ffd21e" size="12" />
                <span>{{ course.rating }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="bottom-actions">
        <van-button
          type="primary"
          size="large"
          block
          @click="startLearning"
          :loading="loading"
        >
          {{ userProgress?.progress > 0 ? '继续学习' : '开始学习' }}
        </van-button>
      </div>
    </div>

    <!-- 空状态 -->
    <van-empty
      v-else
      image="search"
      description="课程不存在或已下架"
      class="empty-state"
    >
      <van-button
        round
        type="primary"
        class="bottom-button"
        @click="router.go(-1)"
      >
        返回上一页
      </van-button>
    </van-empty>
    </div>
  </div>
</template>

<script setup name="CourseDetailPage" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { StudyService } from '@/api/services';
import type { Course } from '@/api/index';

const router = useRouter();
const route = useRoute();

// 响应式数据
const courseDetail = ref<Course | null>(null);
const userProgress = ref<any>(null);
const courseChapters = ref<any[]>([]);
const courseLessons = ref<any[]>([]); // 扁平化的课时列表，用于开始学习功能
const relatedCourses = ref<Course[]>([]);
const loading = ref(false);

// 默认课程数据
const defaultCourse: Course = {
  id: 1,
  title: '普通话基础发音训练',
  description: '从零开始学习普通话标准发音，掌握声母、韵母、声调的正确发音方法',
  cover: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/course-cover-1.png',
  instructor: '张老师',
  rating: 4.8,
  studentCount: 1256,
  duration: 3600,
  difficulty: 'beginner',
  categoryId: 1,
  tags: ['基础', '发音', '声调'],
  price: 0,
  originalPrice: 99,
  isRecommended: true,
  createdAt: '2024-01-01',
  updatedAt: '2024-01-01'
};

// 默认课程章节
const defaultLessons = [
  {
    id: 1,
    title: '第一课：声母基础',
    description: '学习21个声母的标准发音',
    duration: 1800,
    videoUrl: 'https://example.com/video1.mp4',
    isCompleted: false,
    isLocked: false
  },
  {
    id: 2,
    title: '第二课：韵母训练',
    description: '掌握39个韵母的发音技巧',
    duration: 2100,
    videoUrl: 'https://example.com/video2.mp4',
    isCompleted: false,
    isLocked: false
  },
  {
    id: 3,
    title: '第三课：声调练习',
    description: '四个基本声调的发音规律',
    duration: 1500,
    videoUrl: 'https://example.com/video3.mp4',
    isCompleted: false,
    isLocked: true
  }
];

// 默认相关课程
const defaultRelatedCourses: Course[] = [
  {
    id: 2,
    title: '普通话进阶训练',
    description: '提升普通话水平的进阶课程',
    cover: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/course-cover-2.png',
    instructor: '李老师',
    rating: 4.9,
    studentCount: 856,
    duration: 5400,
    difficulty: 'intermediate',
    categoryId: 1,
    tags: ['进阶', '语调', '语音'],
    price: 0,
    originalPrice: 199,
    isRecommended: true,
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01'
  }
];

// 页面方法
const onClickLeft = () => {
  router.go(-1);
};

const handleShare = () => {
  showToast('分享功能开发中...');
};

const playIntroVideo = () => {
  showToast('播放课程介绍视频');
  // 这里可以播放课程介绍视频
};

const playLesson = (lesson: any) => {
  if (lesson.isLocked) {
    showToast('请先完成前面的课程');
    return;
  }
  
  // 跳转到视频播放页面
  router.push(`/video/${lesson.id}?courseId=${route.params.id}&title=${encodeURIComponent(lesson.title)}`);
};

const startLearning = () => {
  // 找到第一个未完成的课程
  const nextLesson = courseLessons.value.find(lesson => !lesson.isCompleted && !lesson.isLocked);
  if (nextLesson) {
    playLesson(nextLesson);
  } else {
    showToast('课程已全部完成');
  }
};

const goToCourse = (courseId: number) => {
  router.push(`/course/${courseId}`);
};

// 工具函数
const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  }
  return `${minutes}分钟`;
};

const formatStudyTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  }
  return `${minutes}分钟`;
};

const getDifficultyType = (difficulty: string): string => {
  const types: Record<string, string> = {
    'beginner': 'success',
    'intermediate': 'warning',
    'advanced': 'danger'
  };
  return types[difficulty] || 'default';
};

const getDifficultyText = (difficulty: string): string => {
  const texts: Record<string, string> = {
    'beginner': '初级',
    'intermediate': '中级',
    'advanced': '高级'
  };
  return texts[difficulty] || '未知';
};

// 加载课程数据
const loadCourseDetail = async () => {
  try {
    loading.value = true;
    const courseId = Number(route.params.id);

    console.log('开始加载课程详情，ID:', courseId);

    // 调用API获取课程详情
    const courseResult = await StudyService.getCourseDetail(courseId);

    if (courseResult && courseResult.data) {
      courseDetail.value = courseResult.data;

      // 从课程详情中提取章节和课时信息
      if (courseResult.data.chapters && Array.isArray(courseResult.data.chapters)) {
        courseChapters.value = courseResult.data.chapters;

        // 创建扁平化的课时列表，用于开始学习功能
        const allLessons: any[] = [];
        courseResult.data.chapters.forEach((chapter: any) => {
          if (chapter.lessons && Array.isArray(chapter.lessons)) {
            chapter.lessons.forEach((lesson: any) => {
              allLessons.push({
                ...lesson,
                chapterTitle: chapter.title,
                chapterDescription: chapter.description
              });
            });
          }
        });
        courseLessons.value = allLessons;

        console.log('✅ 课程章节加载成功，章节数:', courseChapters.value.length, '课时数:', courseLessons.value.length);
      } else {
        courseChapters.value = [];
        courseLessons.value = [];
        console.log('⚠️ 课程章节数据为空');
      }

      console.log('✅ 课程详情加载成功');
    } else {
      console.log('⚠️ 课程详情数据为空');
      courseDetail.value = null;
      courseChapters.value = [];
      courseLessons.value = [];
    }

    // 加载相关推荐课程
    try {
      const relatedResult = await StudyService.getRecommendedCourses({
        page: 1,
        limit: 5,
        category: courseDetail.value?.category?.id
      });

      if (relatedResult && relatedResult.data && relatedResult.data.list) {
        // 过滤掉当前课程
        relatedCourses.value = relatedResult.data.list.filter(course => course.id !== courseId);
        console.log('✅ 相关课程加载成功，数量:', relatedCourses.value.length);
      } else {
        relatedCourses.value = [];
        console.log('⚠️ 相关课程数据为空');
      }
    } catch (error) {
      console.error('加载相关课程失败:', error);
      relatedCourses.value = [];
    }

  } catch (error) {
    console.error('加载课程详情失败:', error);
    showToast('加载课程详情失败');

    // 错误时清空数据
    courseDetail.value = null;
    courseChapters.value = [];
    courseLessons.value = [];
    relatedCourses.value = [];
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  loadCourseDetail();
});
</script>

<style lang="scss" scoped>
.course-detail-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 18.66667vw; // 为底部操作栏留出空间
}

.page-content {
  padding: 4.26667vw;
}

// 课程头部
.course-header {
  background: #fff;
  border-radius: 2.13333vw;
  overflow: hidden;
  margin-bottom: 4.26667vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.course-cover {
  position: relative;
  height: 53.33333vw;

  .cover-image {
    width: 100%;
    height: 100%;
  }

  .play-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2.13333vw;
    background: rgba(0, 0, 0, 0.5);
    padding: 4.26667vw;
    border-radius: 2.13333vw;
    cursor: pointer;

    .play-text {
      color: #fff;
      font-size: 3.73333vw;
    }
  }
}

.course-info {
  padding: 4.26667vw;
}

.course-title {
  font-size: 5.33333vw;
  font-weight: 600;
  color: #323233;
  margin-bottom: 2.13333vw;
  line-height: 1.4;
}

.course-description {
  font-size: 3.73333vw;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 4.26667vw;
}

.course-meta {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2.13333vw;
  margin-bottom: 4.26667vw;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 1.06667vw;
  font-size: 3.46667vw;
  color: #646566;
}

.difficulty-tag {
  display: flex;
  justify-content: flex-start;
}

// 进度部分
.progress-section {
  background: #fff;
  border-radius: 2.13333vw;
  padding: 4.26667vw;
  margin-bottom: 4.26667vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.13333vw;

  h3 {
    font-size: 4.26667vw;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .progress-text {
    font-size: 3.73333vw;
    color: #1989fa;
    font-weight: 600;
  }
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 2.13333vw;
  font-size: 3.46667vw;
  color: #646566;
}

// 课程章节
.lessons-section {
  background: #fff;
  border-radius: 2.13333vw;
  padding: 4.26667vw;
  margin-bottom: 4.26667vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 4.26667vw;
  font-weight: 600;
  color: #323233;
  margin: 0 0 4.26667vw 0;
}

.lessons-list {
  display: flex;
  flex-direction: column;
  gap: 3.2vw;
}

.chapter-section {
  margin-bottom: 5.33333vw;

  .chapter-header {
    padding: 2.66667vw 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 2.66667vw;

    .chapter-title {
      font-size: 4.26667vw;
      font-weight: 600;
      color: #333;
      margin: 0 0 1.33333vw 0;
    }

    .chapter-description {
      font-size: 3.46667vw;
      color: #666;
      margin: 0;
    }
  }
}

.lesson-item {
  display: flex;
  align-items: center;
  gap: 3.2vw;
  padding: 3.2vw;
  border-radius: 2.13333vw;
  background: #f7f8fa;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    background: #ebedf0;
  }
}

.lesson-number {
  width: 8.53333vw;
  height: 8.53333vw;
  border-radius: 50%;
  background: #1989fa;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3.46667vw;
  font-weight: 600;
  flex-shrink: 0;
}

.lesson-content {
  flex: 1;
}

.lesson-title {
  font-size: 4vw;
  font-weight: 600;
  color: #323233;
  margin: 0 0 1.06667vw 0;
}

.lesson-description {
  font-size: 3.46667vw;
  color: #646566;
  margin: 0 0 2.13333vw 0;
  line-height: 1.4;
}

.lesson-meta {
  display: flex;
  align-items: center;
  gap: 2.13333vw;
}

.lesson-duration {
  font-size: 3.2vw;
  color: #969799;
}

.lesson-action {
  flex-shrink: 0;
}

// 相关推荐
.related-section {
  background: #fff;
  border-radius: 2.13333vw;
  padding: 4.26667vw;
  margin-bottom: 4.26667vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.related-courses {
  display: flex;
  gap: 3.2vw;
  overflow-x: auto;
  padding-bottom: 2.13333vw;

  &::-webkit-scrollbar {
    display: none;
  }
}

.related-course {
  flex-shrink: 0;
  width: 42.66667vw;
  cursor: pointer;
}

.related-cover {
  width: 100%;
  height: 24vw;
  border-radius: 2.13333vw;
  margin-bottom: 2.13333vw;
}

.related-info {
  .related-title {
    font-size: 3.73333vw;
    font-weight: 600;
    color: #323233;
    margin: 0 0 1.06667vw 0;
    line-height: 1.3;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .related-meta {
    display: flex;
    align-items: center;
    gap: 1.06667vw;
    font-size: 3.2vw;
    color: #646566;
  }
}

// 底部操作栏
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 4.26667vw;
  border-top: 1px solid #ebedf0;
  z-index: 100;
}

// 响应式设计
@media (min-width: 768px) {
  .course-detail-page {
    max-width: 768px;
    margin: 0 auto;
  }
}

// 空状态样式
.empty-state {
  padding: 8vw 4vw;

  .van-empty__description {
    color: #969799;
    font-size: 3.5vw;
    margin-top: 3vw;
  }

  .bottom-button {
    margin-top: 4vw;
    padding: 0 6vw;
    height: 9vw;
    font-size: 3.5vw;
  }
}

// 加载状态样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12vw 0;

  .van-loading {
    font-size: 3.5vw;
  }
}
</style>
